'use strict';

const _ = require('lodash');

exports.index = async ctx => {
  const { query } = ctx.request;
  let pageSize = 10;
  if (query.pageSize) pageSize = Number(query.pageSize);
  const where = {};
  const { id } = query;
  if (id) where.id = id;
  const options = {
    limit: pageSize,
    offset: query.currentPage ? pageSize * (query.currentPage - 1) : 0,
    order: [
      [ 'id', 'DESC' ],
    ],
    raw: true,
    where,
  };
  const {
    count: total, rows: list,
  } = await ctx.model.FeedBack.findAndCountAll(options);
  ctx.body = {
    list,
    pagination: {
      total,
      pageSize,
      current: parseInt(query.currentPage, 10) || 1,
    },
  };
};

exports.create = async ctx => {
  const { app } = this;
  ctx.validate({
    content: { type: 'string' },
  });
  const loginService = app.weapp.LoginService.create(ctx.request, ctx.response);
  const { userInfo } = await loginService.check();
  console.log('UserController userInfoFromWeapp userInfo', userInfo);
  const { openId } = userInfo;
  const weappUser = await this.ctx.model.WechatAccount.findByPk(openId);
  const { userId } = weappUser;
  const user = await ctx.model.User.findByPk(userId);
  const { content } = ctx.request.body;
  const data = { content, name: user.name };
  ctx.body = await ctx.model.FeedBack.create(_.pick(
    data,
    [ 'content', 'name' ]
  ));
};

exports.show = async ctx => {
  const options = { raw: true };
  const feedback = await ctx.model.FeedBack.findByPk(ctx.params.id, options);
  if (feedback) {
    ctx.body = feedback;
  } else {
    ctx.status = 404;
  }
};

exports.update = async ctx => {
  const feedback = await ctx.model.FeedBack.findByPk(ctx.params.id);
  if (feedback) {
    ctx.validate({
      name: { type: 'string', required: false },
      content: { type: 'string', required: false },
      status: { type: 'string', require: false },
    });
    ctx.body = await feedback.update(_.pickBy(
      _.pick(
        ctx.request.body,
        [ 'name', 'content', 'status' ]
      ),
      value => value !== null
    ));
  } else {
    ctx.status = 404;
  }
};

exports.destroy = async ctx => {
  const feedback = await ctx.model.FeedBack.findByPk(ctx.params.id);
  if (feedback) {
    await feedback.destroy();
    ctx.status = 204;
  } else {
    ctx.status = 404;
  }
};
